package com.xayy.health.core.exception;

import cn.hutool.core.io.IORuntimeException;
import cn.kawins.base.result.ResultBody;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.List;

/**
 * 异常处理器
 *
 * @author houchengwei
 */
@RestControllerAdvice
public class HealthExceptionHandler {

    /**
     * 处理自定义异常
     */
    @ExceptionHandler(HealthException.class)
    public ResultBody handleRRException(HealthException e) {
        ResultBody r = new ResultBody();
        r.setCode(e.getCode());
        r.setMessage(e.getMsg());
        return r;
    }

    /**
     * 处理hutool发出http请求拒绝连接的异常
     */
    @ExceptionHandler(IORuntimeException.class)
    public ResultBody iORuntimeException(IORuntimeException e) {
        return ResultBody.failed("后台请求相关接口失败，请检查配置文件接口地址是否正确：" + e.getMessage());
    }

    /**
     * 处理未知异常
     */
    @ExceptionHandler(Exception.class)
    public ResultBody unkown(Exception e) {
        e.printStackTrace();
        return ResultBody.failed("未知异常，请查看日志处理");
    }

    @ResponseBody
    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    public ResultBody handleValidException(MethodArgumentNotValidException e) {
        BindingResult bindingResult = e.getBindingResult();
        StringBuilder message = new StringBuilder();
        if (bindingResult.hasErrors()) {
            List<ObjectError> allErrors = bindingResult.getAllErrors();
            for (ObjectError allError : allErrors) {
                message.append(allError.getDefaultMessage()).append(", ");
            }
        }
        return ResultBody.failed(message.toString());
    }
}
